<?php

namespace app\admin\controller;

use app\admin\controller\Admin;
use think\Db;

/**
 * @title 采购
 */
class Purchase extends Admin {

    /**
     * @title 采购
     */
    public function add() {

        if (request()->isPost()) {

            $product_id = request()->post('product_id');

            // 供应商 
            $supplier = model('product_supplier')->column('company', 'id');

            // 产品信息
            $product = Db::name('product')->where('id', $product_id)->find();


            return $this->renderSuccess('', '', compact('supplier', 'product'));
        }

        return view();
    }

    /**
     * @title 采购提交  
     */
    public function add_submit() {

        if (request()->isPost()) {
            $post = request()->post();

            //产品
            $product_ids = isset($post['product_ids']) ? $post['product_ids'] : [];
            $product_ids = array_filter($product_ids);
            //数量
            $quantity = isset($post['quantity']) ? $post['quantity'] : [];
            //供应商
            $supplier = isset($post['supplier']) ? $post['supplier'] : [];
            //价格
            $group_price = isset($post['group_price']) ? $post['group_price'] : [];

            // 准备产品列表数据
            $total_quantity = 0;
            $total_price = 0;
            $products = [];

            foreach ($product_ids as $key => $product_id) {



                if (empty($quantity[$key]) || !preg_match("/^[1-9][0-9]*$/", $quantity[$key]))
                    return $this->renderError('数量有误');

                if (!is_numeric($group_price[$key]))
                    return $this->renderError('金额有误');

                if (!empty($product_id) && is_numeric($product_id) && ($product = Db::name('product')->where('id', $product_id)->find())) {

                    // 放到哪个仓库
                    $product['supplier_id'] = $supplier[$key];
                    // 放了多少数量 
                    $product['quantity'] = $quantity[$key];
                    // 放入的金额是多少
                    $product['group_price'] = $group_price[$key];

                    // 数据总计
                    $total_quantity += $quantity[$key];
                    // 金额总计
                    $total_price += $quantity[$key] * $group_price[$key];

                    $products[] = $product;
                }
            }

            if (empty($products)) {
                return $this->renderError('请选择采购产品');
            }


            // 总金额校验
            if ($post['total_price'] != $total_price) {
                return $this->renderError('总金额有误，请修正后重新提交');
            }


            // 准备要采购的数据
            $post['total_quantity'] = $total_quantity;
            $post['total_price'] = $total_price;




            // dd($products);


            model('product_purchase_order')->add_submit($post, $products);
            if (model('product_purchase_order')->hasError()) {
                model('operate')->failure(model('product_purchase_order')->getError());
                return $this->renderError(model('product_purchase_order')->getError());
            }
            model('operate')->success('采购成功');
            return $this->renderSuccess('采购成功', 'reload');
        }
    }

    /**
     * @title 采购单记录
     */
    public function query() {


        if (!isset($_GET['timea']))
            $_GET['timea'] = date('Y-m-d', strtotime("-30 day"));
        if (!isset($_GET['timeb']))
            $_GET['timeb'] = date('Y-m-d');


        $count = model('product_purchase_order')->model_where()->count('distinct a.id');
        $lists = model('product_purchase_order')->model_where()->group('a.id')->paginate(input('get.page_size', 10), $count, ['query' => request()->get()]);



        $this->assign('count', $count);
        $this->assign('lists', $lists);
        $this->assign('pages', $lists->render());

        return view();
    }

    /**
     * @title 入库记录
     */
    public function storage_history($id) {


        $lists = Db::name('rel_purchase_storage')->where('purchase_order_data_id', $id)->select();

        $this->assign('lists', $lists);

        return view();
    }

    /**
     * @title 采购入库
     * @param type $id
     */
    public function storage($id) {



        if (request()->isPost()) {

            $post = request()->post();

            if (empty($post['warehouse']))
                return $this->renderError('请选择仓库');
            if (empty($post['quantity']) || !is_numeric($post['quantity']))
                return $this->renderError('请确定退货数量');


            // 检查 是否已经全部入库
            $order_data = model('product_purchase_order_data')->get($id);



            if ($order_data['puts'] >= $order_data['quantity'])
                return $this->renderError('该产品已经完全入库');


            $quantity = $order_data['quantity'] - $order_data['puts'];
            if (empty($order_data['quantity']) || $quantity < $post['quantity'])
                return $this->renderError('入库数量不能大与' . $quantity);


            // 组装订单信息
            // 总数量
            $post['quantity'] = $post['quantity'];
            // 总额
            $post['amount'] = $post['quantity'] * $post['group_price'];
            // 入库类型
            $post['type'] = 1;
            // 
            $post['supplier'] = $order_data['supplier_id'];



            // 组装产品信息
            $product['warehouse'] = $post['warehouse'];
            $product['id'] = $order_data['product_id'];
            $product['s_id'] = $order_data['supplier_id'];
            $product['group_price'] = $post['group_price'];
            $product['quantity'] = $post['quantity'];



            // 交给model执行
            model('product_purchase_order_data')->storage($id, $post, [$product]);
            if (model('product_purchase_order_data')->hasError()) {
                return $this->renderError(model('product_purchase_order_data')->getError());
            }



            return $this->renderSuccess('入库成功', 'reload');
        }



        // 加载order_data单条记录
        $this->assign('order_data', model('product_purchase_order_data')->get($id));


        // 仓库
        $this->assign('warehouse', model('product_warehouse')->model_where()->where('pwu.u_id', UID)->select());

        return view();
    }

    /**
     * @title 撤销账单
     */
    public function query_delete($id) {

        empty($id) && exit();


        


        model('product_purchase_order')->query_delete($id);
        if (model('product_purchase_order')->hasError()) {
            model('operate')->failure(model('product_purchase_order')->getError());
            return $this->renderError(model('product_purchase_order')->getError());
        }
        model('operate')->success('撤销账单成功');
        return $this->renderSuccess('', 'reload');
    }

}
